package cn.iphone.NPlayer.mq.consumer;

import cn.iphone.NPlayer.constants.MqConstants;
import cn.iphone.NPlayer.domain.MessageSms;
import cn.iphone.NPlayer.dto.MessageSmsDto;
import cn.iphone.NPlayer.dto.UserSmsDto;
import cn.iphone.NPlayer.service.IMessageSmsService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * @author mq消费
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = "sms-message-group",
                            topic = MqConstants.COURSE_SMS_TOPIC,
                            selectorExpression = MqConstants.COURSE_SMS_TAG)
public class CourseSendMessageConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IMessageSmsService messageSmsService;

    @Override
    public void onMessage(MessageExt message) {
        // 1.获取消息体，为空不消费
        byte[] body = message.getBody();
        if (body == null || body.length == 0) {
            return;
        }
        // 2.转换消息体
        MessageSmsDto messageSmsDto = JSONObject.parseObject(new String(body, StandardCharsets.UTF_8), MessageSmsDto.class);
        // 3.保存消息导数据库
        saveSmsMessage(messageSmsDto);
        // 4.调用工具类发送短信，我直接打印了
        log.info("发送短信成功，消息标题为：{}, 消息内容为：{}, 用户电话为：{}", messageSmsDto.getTitle(), messageSmsDto.getContent(), messageSmsDto.getUsers());
    }

    private void saveSmsMessage(MessageSmsDto messageSmsDto) {
        MessageSms messageSms = new MessageSms();
        messageSms.setTitle(messageSmsDto.getTitle());
        messageSms.setContent(messageSmsDto.getContent());
        messageSms.setSendTime(new Date());
        List<UserSmsDto> users = messageSmsDto.getUsers();
        users.forEach(u->{
            messageSms.setUserId(u.getId());
            messageSmsService.insert(messageSms);
        });
    }
}
